<?php
namespace atlaxy;

use think\App;
use think\exception\HttpResponseException;
use think\Request;

/**
 * 基础控制器封装
 *
 * @author atlaxy
 * @time 2020-09-24
 */
class Controller
{
    /**
     * 应用容器
     * @var App
     */
    public $app;

    /**
     * 请求对象
     * @var Request
     */
    public $request;

    /**
     * 控制器中间键
     * @var array
     */
    protected $middleware = [
    ];
    /**
     * Controller constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $app->request;
        $this->initialize();
    }

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        //在中间件中对user是否合法进行判断
    }

    /**
     * 返回失败的操作
     * @param string $msg 消息内容
     */
    public function jsonFail($msg="操作失败")
    {
        throw new HttpResponseException(json([
            'code' => 0, 'msg' => $msg,
        ]));
    }

    /**
     * 返回成功的操作
     * @param array $data 返回数据
     * @param string $msg 消息内容
     */
    public function jsonSucc( $data = [],$msg="操作成功")
    {
        throw new HttpResponseException(json([
            'code' => 1, 'msg' => $msg, 'data' => $data,
        ]));
    }
    /**
     * 返回需要登陆
     */
    public function needLogin()
    {
        throw new HttpResponseException(json([
            'code' => -1, 'msg' => "请先登录"
        ]));
    }

    /**
     * 快捷分页
     *
     * @param Model $model 要分页的模型名
     * @param string $sort 排序语句
     * @param array $where 筛选条件数组
     * @param boolean $nodeleted 是否过滤delete_time不为0的数据
     * @return array
     */
    public function _page($model,$sort="id desc",$where=[],$nodeleted=true){
        $currentPage = $this->request->get('page',1,'intval');
        if($nodeleted){
            $fields = $model->getTableFields();
            if(in_array('delete_time',$fields)){
                array_push($where,['delete_time','=',0]);
            }
        }
        $count = $model->where($where)->count();
        $totalPage = ceil($count / 20);

        $list = $model->where($where)->order($sort)->limit(($currentPage - 1)*20,20)->select();
        return compact('currentPage','totalPage','list');
    }
}